<?php
namespace app\api\controller\newfile;

use think\Request;
use app\common\model\newmodel\Customer as CustomerModel;
use app\common\model\power\Rolepower;
use app\common\model\newmodel\User as UserModel;
use app\common\model\newmodel\UserAgency;
use app\api\controller\Pub;
use app\api\controller\Base;
use app\common\model\newmodel\ContractOrder;
use app\common\model\newmodel\Factory;
use app\common\model\newmodel\Device as DeviceModel;
use think\facade\Env;

class Orders extends Base
{
    public function initialize(){
		parent::initialize();
		self::is_login();
		Rolepower::powerguard(301002);
	}

    /**
	 * 判断账号是否登录
	 * @return boolean [description]
	 */
	private function is_login(){
		$data = UserModel::is_sessionlogin();
		if (!$data['code']) {
			$data['options'] = 'relogin';
			json($data)->send();
			exit;
		}
	}

    //产品列表
    public function deviceListMore()
    {
        $result=DeviceModel::deviceListMore();
        return json($result);
    }

    //生成订单
    public function productOrder(Request $request)
    {
        $data = $request->post();
        $result = ContractOrder::createProductOrders($data);
        return json($result);
    }

    //订单列表
    public function orderList()
    {
        $userId = Pub::userid();
        $data=input();
        $page = input('page') ?? 1;
        $pageSize = input('pageSize') ?? 1;
        $keyword = input('keyword', '');
        $status = input('status') ?? '';
        $result = ContractOrder::getOrderList($userId, $page, $pageSize, $keyword ,$status);
        return json($result);
    }

    /**
     * 订单状态修改
     */
    public function orderStatusChange(Request $request)
    {
        $data = $request->post();
        if (empty($data['id'])) {
            return json(['code' => 0, 'msg' => '参数不完整']);
        }

        $result = ContractOrder::updateOrderStatus($data);
        return json($result);
    }
    /**
     * 根据合同查看对应的订单列表（一个合同对应多个订单）
     */
    public function getOrdersByContractId(Request $request)
    {
        $data=input();
        if(empty($data['contract_id'])){
            return json(['code' => 0, 'msg' => '参数不完整']);
        }
        $result=ContractOrder::getOrdersByContractId($data['contract_id']);

        return json($result);
    }
    
    /**
     * 订单删除
     */
    public function orderDel()
    {
        $order_id=input('id');
        $res=ContractOrder::where('id',$order_id)->update(['State'=>3]);
        if($res){
            return json([
                'code' =>1,
                'msg'  =>'删除成功'
            ]);
        }else{
            return json([
                'code' =>0,
                'msg'  =>'删除失败'
            ]);
        }
        
    }

    //工厂列表
    public function factoryList()
    {   
        $factroyData=Factory::select()->toArray();
        return myok($factroyData);
    }

    //转单处理
    public function transferOrder()
    {
        $data=input('post.');
        if(empty($data['id']) || empty($data['factory_id'])){
            return json(['code'=>false,'msg'=>'参数不完整']);
        }
        $result=ContractOrder::transferOrder($data['id'],$data['factory_id'],$data['transfer_remark']);
        return json($result);
    }

    //工厂确认订单，确认接受该订单，订单状态为生产中
    public function confirmOrder()
    {
        $id=input('id');
        if(empty($id)){
            return json(['code'=>false,'msg'=>'参数不完整']);
        }
        $result=ContractOrder::confirmOrder($id);
        return json($result);
    }

    //去发货,上传对应的物流单号和一些图片，
    public function goShipGoods()
    {
        $data=input('post.');
        if(empty($data['id']) || empty($data['track_number'])){
            return json(['code'=>false,'msg'=>'参数不完整']);
        }
        $result=ContractOrder::goShipGoods($data);
        return json($result);
    }

    //上传发货凭证
    public function uploadImg(){
		$type = empty(input('type'))?'other':input('type');
		if(!$type=='hawa'||!$type=='buss'||!$type=='acco' || !$type=='productcontract' || !$type=='productorder'){
			$type = 'other';
		}
		try {
			$file = request()->file('img');
		} catch (\Exception $e) {
			return json_encode(['status'=>'error','data'=>$e->getMessage()]);
		}
        // 移动到框架应用根目录/public/uploads/ 目录下
        if(!is_null($file)){
           	try{
           		$save_path = Env::get('root_path').'public\\static' .'\\upimg\\countract\\'.$type.'\\';
	            $info = $file->validate(["size"=>50000000,'ext'=>'jpg,png,gif'])->rule("date")->move($save_path);
	            //echo $save_path. DS . date("Ymd") . DS .  $info->getFilename();
	            $image = \think\Image::open($save_path . '\\' . $info->getSaveName());
	            $image->thumb(2000, 2000)->save($save_path .  '\\' . $info->getSaveName());
	            if($info){//getSaveName();
	                $p=$info->getFilename();
	                return json_encode(['status'=>'ok','data'=>'http://192.168.10.105:8081/'.'static/upimg/countract/'.$type.'/'.date('Ymd',time()).'/'.$p]);
	            }else{
	              return json_encode(['status'=>'error','data'=>$info->getError()]);
	            }
           	} catch (\Exception $e) {
				return json_encode(['status'=>'error','data'=>$e->getMessage()]);
			}
         }else{
              return json_encode(['status'=>'error','data'=>'没有找到需要上传的图片']);
         }
	}

}